// 音乐播放页面
import React, { memo, useEffect, useRef, useState, useCallback } from 'react'
import { shallowEqual, useSelector, useDispatch } from 'react-redux'
import { NavLink } from 'react-router-dom'
import { PlusSquareOutlined, DownloadOutlined, RestOutlined, ClearOutlined, PlayCircleOutlined, StepBackwardOutlined, PauseOutlined, CaretRightOutlined, StepForwardOutlined } from '@ant-design/icons'
import { message, Slider } from 'antd'

import moment from 'moment'
// changeSequenceAction 改变 播放的状态   0 列表循环 1 随机 2 单曲
// changeCurrentIndexAndSongAction 改变 播放的歌曲。 下一首？ 上一首？
import { getSongDetailAction, changeSequenceAction, changeCurrentIndexAndSongAction, changeCurrentLyricIndexAction, deleteBofangListAction, deteleOneAction } from './store/actions'

import { getSongMp3Src } from '../../api/gequApi'
import { PlayerBox } from './style'
import playerImg from '../../assets/images/wave.gif'




export default memo(function Player(props) {
  // state
  const audioRef = useRef()
  const [lyricTranslateY, setLyricTranslateY] = useState(0)
  //const volumeRef = useRef() // 音量的 DOM
  const [volumeProgress, setVolumeProgress] = useState(100) // 控制音量的进度条的进度
  const [showVolume, setShowVolume] = useState(true) // false 是静音，true 有音
  const [showPlayOrStop, setShowPlayOrStop] = useState(false)// 控制 底部控制栏  是 显示 暂停 按钮 还是 播放
  const [currentTime, setCurrentTime] = useState(0); // 实时的播放进度
  const [progress, setProgress] = useState(0);  // 进度条的百分比
  const [isChanging, setIsChanging] = useState(false); // 进度条当前是否正在发生改变
  const [threeChooseOne] = useState(["liebiaoxunhuan", "suijibofang", "danquxunhuan"]) // 播放状态，0 列表循环 1 随机 2 单曲
  const {
    playList,
    currentSong,
    sequence, // 循环 还是  单曲循环 还是 随机      0 列表循环 1 随机 2 单曲
    lyricList,
    currentLyricIndex
  } = useSelector(state => ({
    playList: state.getIn(["player", "playList"]),
    currentSong: state.getIn(["player", "currentSong"]),
    sequence: state.getIn(["player", "sequence"]),
    lyricList: state.getIn(["player", "lyricList"]),
    currentLyricIndex: state.getIn(["player", "currentLyricIndex"])
  }), shallowEqual)
  // redux hooks
  const dispatch = useDispatch()
  useEffect(() => {
    // console.log('请求发起');
    // console.log(playList);
    // console.log(porps.match);
    dispatch(getSongDetailAction(props.match.params.id))
  }, [])

  // other hooks
  useEffect(() => {
    setLyricTranslateY(0)

    // console.log('执行了播放音频');
    // audioRef.current.src = getSongMp3Src(currentSong.id);
    getSongMp3Src(currentSong.id).then(res => {
      if (res.data[0].url != null) {
        audioRef.current.src = res.data[0].url
      } else {
        message.error('此歌曲音频暂未找到~~~~');
      }

      // console.log(res);
    })
    // const res = await getSongMp3Src(currentSong.id)
    // audioRef.current.src = res.data[0].url
    // audioRef.current.volume = 0.2   //控制音量

    audioRef.current.play().then(res => {
      setShowPlayOrStop(true);
      console.log('播放成功', currentSong.id);
    }).catch(err => {
      setShowPlayOrStop(false);
      console.dir(err);
    });
  }, [currentSong]);

  const picUrl = (currentSong.al && currentSong.al.picUrl) || ""
  const singerName = (currentSong.ar && currentSong.ar[0].name) || "未知歌手"
  const duration = currentSong.dt || 0;
  const showDuration = moment(duration).format("mm:ss"); // 总时长
  const showCurrentTime = moment(currentTime).format("mm:ss"); // 实时播放进度

  // 播放还是暂停 切换
  const playMusic = useCallback(() => {
    showPlayOrStop ? audioRef.current.pause() : audioRef.current.play();
    setShowPlayOrStop(!showPlayOrStop);
  }, [showPlayOrStop]);
  // 音频 进度 更新的时候执行的函数
  const timeUpdate = (e) => {
    const currentTime = e.target.currentTime;  // 这里返回的是 秒
    // console.log(currentTime);

    if (!isChanging) {
      setCurrentTime(currentTime * 1000);
      setProgress(currentTime * 1000 / duration * 100);
    }

    // 获取歌词
    let i = 0;
    for (; i < lyricList.length; i++) {
      let lyricItem = lyricList[i];
      if (currentTime * 1000 < lyricItem.time) {
        break;
      }
    }
    // 别忘了 剪掉1 ，因为 实时的进度还没到这个地方

    if (currentLyricIndex !== i - 1) {
      dispatch(changeCurrentLyricIndexAction(i - 1));
      const content = lyricList[i - 1] && lyricList[i - 1].content
      message.open({
        key: "lyric", // key 的目的是 让页面始终出现一个 
        content: content,
        duration: 0,
        className: "lyric-class"
      })

      // 动态更新偏移值
      if (currentLyricIndex > 3 || currentLyricIndex < lyricList.length - 3) {
        setLyricTranslateY(-35 * currentLyricIndex)
      }
    }



  }



  // 进度条 组件，值发生变化的时候 执行的函数
  const sliderChange = (value) => {
    // 鼠标 放在进度条的时候，不能让 timeUpdate 事件改变 进度、时间
    setIsChanging(true);
    const currentTime = value / 100 * duration; // 毫秒
    setCurrentTime(currentTime);
    setProgress(value);
  }

  // 进度条组件， 鼠标安下后，抬起的时候，执行的函数
  const sliderAfterChange = (value) => {
    const currentTime = value / 100 * duration / 1000;
    audioRef.current.currentTime = currentTime;
    setCurrentTime(currentTime * 1000);
    setIsChanging(false);

    if (!showPlayOrStop) {
      playMusic()
    }
  }


  // 歌曲播放顺序改变 列表循环？ 单曲？ 随机？
  const changeSequence = () => {
    let currentSequence = sequence + 1;
    if (currentSequence > 2) {
      currentSequence = 0;
    }

    dispatch(changeSequenceAction(currentSequence));
  }

  // 当前音频 播放完成的时候 执行的函数
  const handleMusicEnded = () => {
    if (sequence === 2) { // 单曲循环
      audioRef.current.currentTime = 0;
      audioRef.current.play();
    } else {
      dispatch(changeCurrentIndexAndSongAction(1));
    }
  }

  //  点击 上一首 或者下一首
  const changeMusic = (tag) => {
    dispatch(changeCurrentIndexAndSongAction(tag));
  }

  // 点击 歌曲展示列表的某一个 歌曲的  播放按钮的时候
  const toggleSong = (id) => {
    dispatch(getSongDetailAction(id))
  }

  const mainConentLeftAnniu = flag => {
    if (flag < 4) {
      message.error("此功能暂未开放", flag)
    } else {
      // 清空列表
      dispatch(deleteBofangListAction())
      audioRef.current.src = ""
      setShowPlayOrStop(false)
    }
  }

  // 音量 进度的 事件
  const volumeChange = (value) => {
    // console.log(value, '滑动');

    if (value == 0) {
      setShowVolume(false)
    } else {
      setShowVolume(true)
    }
    setVolumeProgress(value)
    audioRef.current.volume = volumeProgress / 100
  }
  // 音量的进度条，鼠标抬起的时候
  const volumeAfterChange = (value) => {
    // console.log(value, '抬起');
    if (value == 0) {
      setShowVolume(false)
    } else {
      setShowVolume(true)
    }
    setVolumeProgress(value)
    audioRef.current.volume = volumeProgress / 100
  }

  // 点击 静音图标 或者非静音图标的时候
  const clickJingyinOrNojingyin = () => {

    if (!showVolume == false) {
      // 静音 
      console.log('静音了');
      audioRef.current.volume = 0
      setVolumeProgress(0)
    } else {
      audioRef.current.volume = 1
      setVolumeProgress(100)
    }
    setShowVolume(!showVolume)
  }
  return (
    <div>
      <PlayerBox bg={picUrl}>
        <div className="main">
          <div className="main_content">
            <div className="main_content_left">
              {/* 前面的四个按钮 */}
              <div className="main_content_left_anniu">
                <div onClick={e => mainConentLeftAnniu(1)}>
                  <PlusSquareOutlined />
                  收藏
                </div>
                <div onClick={e => mainConentLeftAnniu(2)}>
                  <DownloadOutlined />
                  下载
                </div>
                <div onClick={e => mainConentLeftAnniu(3)}>
                  <RestOutlined />
                  删除
                </div>
                <div onClick={e => mainConentLeftAnniu(4)}>
                  <ClearOutlined />
                  清空列表
                </div>
              </div>
              {/* 歌曲列表整体 */}
              <div className="main_content_left_list">
                <div className="main_content_left_list_item" style={{ marginBottom: "10px" }}>
                  <div className="main_content_left_list_nanniu">
                    <span className="icon-fangxingweixuanzhong iconfont"></span>
                    <div className="main_content_left_list_nanniu_img">

                    </div>
                    <i>1</i>
                  </div>
                  <div className="main_content_left_list_name">歌曲</div>
                  <div className="main_content_left_list_author" >作者</div>
                  <div className="main_content_left_list_time">时长</div>
                </div>

                {/* 歌曲列表 */}
                <div style={{ overflowY: "scroll", height: "840px" }} className="gundongtiao">
                  {/* 每一条歌曲 */}
                  {
                    playList.map((item, index) => {
                      return (
                        <div className="main_content_left_list_item" key={item.id}>
                          <div className="main_content_left_list_nanniu">
                            <span className="icon-fangxingweixuanzhong iconfont"></span>
                            <div className="main_content_left_list_nanniu_img">
                              {item.id == currentSong.id && showPlayOrStop && (<img src={playerImg} />)}
                            </div>

                            <i>{index + 1}</i>
                          </div>
                          <div className="main_content_left_list_name">
                            <div className="main_content_left_list_name_title">
                              {item.name}
                            </div>
                            <div className="main_content_left_list_name_anniu">
                              {/* 播放歌曲按钮 */}
                              <PlayCircleOutlined onClick={e => { toggleSong(item.id) }} />
                              {/* 删除按钮   删除的时候 要返回新的歌曲列表和 要播放歌曲的信息*/}
                              <RestOutlined onClick={e => { dispatch(deteleOneAction(item.id)) }} />
                            </div>
                          </div>
                          <div className="main_content_left_list_author" >{item.ar && item.ar[0].name}</div>
                          <div className="main_content_left_list_time">{moment(item.dt).format("mm:ss")}</div>
                        </div>
                      )
                    })
                  }


                </div>
              </div>
            </div>
            <div className="main_content_right">

              <div className="bg">
                <img src={currentSong.al && currentSong.al.picUrl} alt="歌曲主图" />
              </div>
              <div className="name">
                歌手:&nbsp; <i>{currentSong && currentSong.name}</i>
              </div>
              <div className="author">
                作者: &nbsp;<i>{currentSong.ar && currentSong.ar[0].name}</i>
              </div>
              <div className="gecigundong">
                <div className="gecigundongBox" style={{ transform: `translateY(${lyricTranslateY}px)` }}>
                  {
                    lyricList.map((item, index) => {
                      return (
                        <p className={currentLyricIndex == index ? "active" : ""} key={index}>{item.content}</p>
                      )
                    })
                  }
                </div>
              </div>
            </div>
          </div>
          <div className="main_footer">
            {/* 前进 暂停播放  下一个 */}
            <div className="control">
              <StepBackwardOutlined style={{ fontSize: "40px" }} onClick={e => changeMusic(-1)} />
              {showPlayOrStop ?
                (<CaretRightOutlined style={{ fontSize: "50px" }} onClick={e => playMusic()} />)
                :
                (<PauseOutlined style={{ fontSize: "50px" }} onClick={e => playMusic()} />)
              }
              <StepForwardOutlined style={{ fontSize: "40px" }} onClick={e => changeMusic(1)} />
            </div>
            <div className="progressBox">
              <div className="progressBox_info">
                {/* 左边是  名字+作者 */}
                <div className="progressBox_info_name">
                  <NavLink to="/">{currentSong.name}</NavLink> <i>-</i> <NavLink to="/">{
                    // currentSong.ar && currentSong.ar[0].name
                    singerName
                  }</NavLink>
                </div>
                {/* 右边是 总进度 和 当前进度 */}
                <div className="progressBox_info_time">
                  {showCurrentTime} <i>/</i> {showDuration}
                </div>
              </div>
              <div className="progressBox_progress">
                <Slider defaultValue={0} value={progress} tooltipVisible={false} onChange={sliderChange} onAfterChange={sliderAfterChange} />
              </div>
            </div>
            <div style={{ display: "flex", height: "60px", alignItems: "center" }}>
              <div className="other">
                <i className={"iconfont icon-" + (threeChooseOne[sequence])} onClick={e => changeSequence()}></i>
                {/* <i className="iconfont icon-liebiaoxunhuan"></i> */}
                {/* <i className="iconfont icon-suijibofang"></i>
              <i className="iconfont icon-danquxunhuan"></i> */}

                <i className="iconfont icon-pinglun"></i>

                {/* 静音 还是  非静音 */}
                {showVolume ? <i className="iconfont icon-24gl-volumeHigh" onClick={e => { clickJingyinOrNojingyin() }}></i> : <i className="iconfont icon-24gl-volumeCross" onClick={e => { clickJingyinOrNojingyin() }}></i>}
                {/* 控制音量的进度条 */}

              </div>
              <div className="yinliang">
                <Slider defaultValue={volumeProgress} value={volumeProgress} tooltipVisible={false} onChange={volumeChange} onAfterChange={volumeAfterChange} />
              </div>
            </div>

          </div>
        </div>
        <div className="PlayerBox_bg"></div>
        <audio ref={audioRef} onTimeUpdate={e => timeUpdate(e)} onEnded={e => handleMusicEnded(e)} />
      </PlayerBox>
    </div>
  )
})
